#include <malloc.h>

#include "securec.h"
#include "header.h"

#ifndef UNTITLED2_TREEUTILS_H
#define UNTITLED2_TREEUTILS_H

#endif //UNTITLED2_TREEUTILS_H

void getNum(char str[], char retStrArr[100][10], int *count) {    //1.使用strtok()实现分割
    char test[100] = {0};
    strncpy_s(test, sizeof(test) - 1, (str + 1), strlen(str) - 2);
    char *tmp = strtok(test, " ,");
    if (!tmp) {
        *count = 0;
        return;
    } else {
        strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), tmp);
    }
    while (tmp != NULL) {
        tmp = strtok(NULL, " ,");
        if (NULL == tmp) {
            break;
        }
        if (strcmp(tmp, "null") == 0) {
            strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), "-1");
        } else {
            strcpy_s(retStrArr[(*count)++], sizeof(retStrArr[*count]), tmp);
        }
    }
}

void bfsBuildTree(struct TreeNode *root, int numsArr[], int count) {
    int index = 0;
    int start = 1;
    struct TreeNode *nodes[256] = {0};
    int curCount = 1;
    int tmpCount = 0;
    nodes[0] = root;
    int end = 1;
    while (start < count) {
        for (int i = 0; i < curCount; ++i) {
            struct TreeNode *node = (struct TreeNode *) nodes[index + i];
            if (start < count && numsArr[start] != -1) {
                node->left = malloc(sizeof(struct TreeNode));
                node->left->left = NULL;
                node->left->right = NULL;
                node->left->val = numsArr[start++];
                tmpCount++;
                nodes[end++] = node->left;
            } else {
                start++;
            }
            if (start < count && numsArr[start] != -1) {
                    node->right = malloc(sizeof(struct TreeNode));
                    node->right->left = NULL;
                    node->right->right = NULL;
                    node->right->val = numsArr[start++];
                    tmpCount++;
                    nodes[end++] = node->right;
                } else {
                    start++;
            }
        }
        index += curCount;
        curCount = tmpCount;
        tmpCount = 0;
    }
}

